<?php
/**
 * PHPECS社交电商系统，使用thinkphp框架+MySQL数据库编写的小程序商城系统，基于LGPL协议开源授权
 * @package phpecs
 * @author qq(123865789)
 * @copyright 2018-2020 深圳塔灯网络科技有限公司
 * @version 2.0
 * @license http://www.phpecs.com/lgpl.html phpecs开源授权协议：GNU Lesser General Public License
 **/

// 应用公共文件
// 异常错误报错级别
error_reporting(E_ERROR | E_PARSE );

//上传图片
function upload($catalog){
    // 获取表单上传文件 例如上传了001.jpg
    $file = request()->file('file');
    // 移动到框架应用根目录/public/uploads/ 目录下
    if($file){
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . $catalog);
        if($info){
            // 成功上传后 获取上传信息
            // 输出 目录信息 并替换反斜杠
            $getSaveName = str_replace("\\", "/", $info->getSaveName());
            $img =  $catalog . '/' . $getSaveName;
            echo json_encode(array('img' => $img, 'code' => 0));
        }else{
            // 上传失败获取错误信息
            echo json_encode(array('code' => 1, 'msg' => $file->getError()));
        }
    }
}

//商品上传图片
function shopUpload($catalog){
    // 获取表单上传文件 例如上传了001.jpg
    $file = request()->file('file');
    // 移动到框架应用根目录/public/uploads/ 目录下
    if($file){
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . $catalog);
        if($info){
            // 成功上传后 获取上传信息
            // 输出 目录信息 并替换反斜杠
            $getSaveName = str_replace("\\", "/", $info->getSaveName());
            $img =  $catalog . '/' . $getSaveName;
            echo json_encode(array('error' => 0, 'url' => $img));
        }else{
            echo json_encode(array('error' => 1));
        }
    }
}

/**
 * 证书上传
 * @param $catalog string 目录
 * @param string $rule string 生成规则
 */
function certificate($catalog, $rule = 'date'){
    // 获取表单上传文件 例如上传了001.jpg
    $file = request()->file('file');
    // 移动到框架应用根目录/public/uploads/ 目录下
    if($file){
        $info = $file->rule($rule)->move(ROOT_PATH . 'public' . DS . $catalog);
        if($info){
            // 成功上传后 获取上传信息
            // 输出 目录信息 并替换反斜杠
            $getSaveName = str_replace("\\", "/", $info->getSaveName());
            $url =  $catalog . '/' . $getSaveName;
            successCode($url);
        }else{
            errorCode('上传失败');
        }
    }
}

//编辑器上传图片
function editorUpload($catalog){
    // 获取表单上传文件 例如上传了001.jpg
    $files = request()->file('file');
    foreach($files as $file){
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . $catalog);
        if($info){
            // 输出 目录信息 并替换反斜杠
            $getSaveName = str_replace("\\", "/", $info->getSaveName());
            $img[] =  '/uploads/' . $catalog . '/' . $getSaveName;
        }
    }
    if ($img){
        echo json_encode(array('errno' => 0, 'data' => $img));
    }else{
        echo json_encode(array('errno' => 1));
    }
}

//生成验证码
function phoneCode(){
    $str = '';
    for($i=0;$i<6;$i++) {
        $val = rand(0,9);
        $str .= $val;
    }
    $info = \app\hgapi\model\system\Verify::getVerifyInfo(['code' => $str], '');
    if($info){
        phoneCode();
    }else{
        return $str;
    }
}

//发送post请求
function post($url, $param = ''){
    $header = array(
        "Content-type: text/xml;charset=\"utf-8\""
    );//定义content-type为xml,注意是数组
    $ch = curl_init ();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 兼容本地没有指定curl.cainfo路径的错误
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
    $data = curl_exec($ch);
    curl_close($ch);
    if(curl_errno($ch)){
        // 显示报错信息；终止继续执行
        return curl_error($ch);
    }else{
        return $data;
    }
}


/**发送模板消息
 * @param $id int //模板编号
 * @param $openid string //用户openid
 * @param $prepay_id string //用户支付id
 * @param $data array //参数
 */
function template($id, $openid, $prepay_id, $arr){
    $access_token = access_token();
    $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' . $access_token;
    $template_id = db('template')->where('id', $id)->value('template_id');
    $data = [];
    for ($i = 0; $i < count($arr); $i++){
        $key = $i + 1;
        $data["keyword$key"]['value'] = $arr[$i];
    }
    $param = array(
        'touser' => $openid,
        'template_id' => $template_id,
        "form_id" => $prepay_id,
        "data" => $data
    );
    $param = json_encode($param); //参数转换为json格式
    return post($url, $param);
}

//小程序秘钥
function secret(){
    $secret = \app\admin\model\system\Secret::getSecretInfo();
    return $secret;
}

//获取access_token
function access_token(){
    if (!cache('access_token')){
        //获取凭证access_token
        $secret = secret();
        $json = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $secret['appid'] .
            '&secret=' . $secret['secret_key'];
        header("Content-Type: application/json");
        $contents = file_get_contents($json);
        $contents = json_decode($contents, true); //转为数组
        $access_token = $contents['access_token'];
        cache('access_token', $access_token, 7200);
        return $access_token;
    }else{
        $access_token = cache('access_token');
        return $access_token;
    }
}

//生成验证码
function createImg($access_token, $scene, $page = 'pages/loading/loading', $width = 300){
    $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' . $access_token;
    $param = [
        'scene' => $scene,
        'page' => $page,
        "width" => $width
    ];
    $param = json_encode($param); //参数转换为json格式
    return post($url, $param);
}

//业务员获取佣金
function recruit($recruit){
    $reward = db('site')->where('id', 1)->value('reward');
    db('voucher')->where('id', $recruit)->setInc('gold', $reward);
    $data = [
        'gold' => $reward,
        'uid' => $recruit,
        'content' => '业务员下级商户审核成功 增加佣金'.$reward.'元',
        'time' => time()
    ];
    db('gold')->insert($data);
}

/** 超过某个数字就转换单位
 * @param $i int 当前数量
 * @param $number int 大于数量
 * @param $exceed string 大于返回单位
 * @param $under string 小于返回单位
 * @return string
 */
function convert($i, $number, $exceed, $under){
    return $i >= $number ? $i/$number . $exceed : $i . $under;
}

//下级用户充值上级获取佣金
function gold($upper, $myName, $money, $fan = 0){
    //佣金比例(%)
    $find = \app\hgapi\model\system\Site::getSite('ratio, retail_open, retail_type');
    if ($find['retail_open'] == 1){ //分销开启
        $role = \app\hgapi\model\user\UserRole::getRole(['uid' => $upper]);
        if ($find['retail_type'] == 2 || $role['retail'] == 1){
            $gold = $money * $find['ratio'] / 100;
            //增加佣金
            \app\hgapi\model\user\User::incField($upper, 'gold', $fan > 0 ? $fan : $gold);
            $data = [
                'money' => $money,
                'gold' => $fan > 0 ? $fan : $gold,
                'uid' => $upper,
                'user' => $myName,
                'content' => '下级用户'.$myName.'消费成功 增加佣金'.($fan > 0 ? $fan : $gold).'元',
                'time' => time()
            ];
            \app\hgapi\model\user\UserGold::add($data);
        }
    }
}

//数字转中文
function numToWord($num){
    $chiNum = array('零', '一', '二', '三', '四', '五', '六', '七', '八', '九');
    $chiUni = array('','十', '百', '千', '万', '亿', '十', '百', '千');
    $num_str = (string) $num;
    $count = strlen($num_str);
    $last_flag = true; //上一个 是否为0
    $zero_flag = true; //是否第一个
    $temp_num = null; //临时数字
    $chiStr = '';//拼接结果
    if ($count == 2) {//两位数
        $temp_num = $num_str[0];
        $chiStr = $temp_num == 1 ? $chiUni[1] : $chiNum[$temp_num].$chiUni[1];
        $temp_num = $num_str[1];
        $chiStr .= $temp_num == 0 ? '' : $chiNum[$temp_num];
    }else if($count > 2){
        $index = 0;
        for ($i=$count-1;$i>=0;$i--) {
            $temp_num = $num_str[$i];
            if ($temp_num == 0) {
                if (!$zero_flag && !$last_flag ) {
                    $chiStr = $chiNum[$temp_num]. $chiStr;
                    $last_flag = true;
                }
            }else{
                $chiStr = $chiNum[$temp_num].$chiUni[$index%9] .$chiStr;
                $zero_flag = false;
                $last_flag = false;
            }
            $index ++;
        }
    }else{
        $chiStr = $chiNum[$num_str[0]];
    }
    return $chiStr;
}

/**
 * 系统加密方法
 * @param string $data 要加密的字符串
 * @param string $key  加密密钥
 * @param int $expire  过期时间 单位 秒
 * return string
 */
function encrypt($data, $key = 'tadeng666', $expire = 0) {
    $key  = md5($key);
    $data = base64_encode($data);
    $x    = 0;
    $len  = strlen($data);
    $l    = strlen($key);
    $char = '';
    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }
    $str = sprintf('%010d', $expire ? $expire + time():0);
    for ($i = 0; $i < $len; $i++) {
        $str .= chr(ord(substr($data, $i, 1)) + (ord(substr($char, $i, 1)))%256);
    }
    return str_replace(array('+', '/', '='), array('-', '_', ''), base64_encode($str));
}

/**
 * 系统解密方法
 * @param  string $data 要解密的字符串 （必须是think_encrypt方法加密的字符串）
 * @param  string $key  加密密钥
 * return string
 */
function decrypt($data, $key = 'tadeng666'){
    $key    = md5($key);
    $data   = str_replace(array('-', '_'), array('+', '/'), $data);
    $mod4   = strlen($data) % 4;
    if ($mod4) {
        $data .= substr('====', $mod4);
    }
    $data   = base64_decode($data);
    $expire = substr($data,0,10);
    $data   = substr($data,10);
    if($expire > 0 && $expire < time()) {
        return '';
    }
    $x      = 0;
    $len    = strlen($data);
    $l      = strlen($key);
    $char   = $str = '';
    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }
    for ($i = 0; $i < $len; $i++) {
        if (ord(substr($data, $i, 1))<ord(substr($char, $i, 1))) {
            $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
        }else{
            $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
        }
    }
    return base64_decode($str);
}

/**
 * 成功返回
 */
function successCode($data){
    echo json_encode(['code' => 200, 'data' => $data]);
}

/**
 *失败返回
 */
function errorCode($msg){
    echo json_encode(['code' => 400, 'msg' => $msg]);
    exit;
}

/**
 * 写日志
 * @param $file
 * @param $content
 */
function logs($content, $file = 'log.txt'){
    return file_put_contents($file, $content, FILE_APPEND);
}

/**
 * 获取指定开始时间戳
 * @param $status
 * @return int|string
 */
function TimeAssign($status)
{
    switch ($status) {
        case 1: //今天
            $toDay = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
            return $toDay;
        case 2: //本周
            $toWeek = mktime(0, 0, 0, date('m'), date('d') - date('w') + 1, date('y'));
            return $toWeek;
        case 3: //本月
            $toMonth = mktime(0, 0, 0, date('m'), 1, date('Y'));
            return $toMonth;
        case 4: //本年
            $toYear = strtotime(date("Y", time()) . "-1" . "-1");
            return $toYear;
        default:
            return '';
    }
}

/**
 * 导出excel表格
 * @param $headerName array 第一行的列名称
 * @param $list array sheet名称
 * @param string $setTitle string $setTitle
 * @param string $fileName string 文件名
 * @return string
 */
function exportExcel($headerName, $list, $setTitle = 'Sheet1', $fileName = 'demo'){
    if (empty($headerName) || empty($list)) {
        return '列名或者内容不能为空';
    }
    if (count($list[0]) != count($headerName)) {
        return '列名跟数据的列不一致';
    }
    //实例化PHPExcel类
    vendor('PHPExcel.Classes.PHPExcel');
    $PHPExcel = new PHPExcel();
    //获得当前sheet对象
    $PHPSheet = $PHPExcel->getActiveSheet();
    //定义sheet名称
    $PHPSheet->setTitle($setTitle);
    //excel的列 这么多够用了吧？不够自个加 AA AB AC ……
    $letter        =    [
        'A','B','C','D','E','F','G','H','I','J','K','L','M',
        'N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
    ];
    //把列名写入第1行 A1 B1 C1 ...
    for ($i=0; $i < count($list[0]); $i++) {
        //$letter[$i]1 = A1 B1 C1  $letter[$i] = 列1 列2 列3
        $PHPSheet->setCellValue("$letter[$i]1", "$headerName[$i]");
    }
    //内容第2行开始
    foreach ($list as $key => $val) {
        //array_values 把一维数组的键转为0 1 2 3 ..
        foreach (array_values($val) as $key2 => $val2) {
            //$letter[$key2].($key+2) = A2 B2 C2 ……
            $PHPSheet->setCellValue($letter[$key2] . ($key+2), $val2);
        }
    }
    $objWriter = PHPExcel_IOFactory::createWriter($PHPExcel, 'Excel2007');
    ob_end_clean();
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . $fileName . '"');
    header('Cache-Control: max-age=0');
    $objWriter->save('php://output');
    exit;
}

/**
 *
 * @param $status
 * @return string
 */
function OrderStatus($status){
    switch ($status){
        case 0:
            $statusName = '待付款';
            break;
        case 1:
            $statusName = '待发货';
            break;
        case 2:
            $statusName = '待收货';
            break;
        case 3:
            $statusName = '已完成';
            break;
        case 4:
            $statusName = '已关闭';
            break;
        case 5:
            $statusName = '退款';
            break;
        case 6:
            $statusName = '活动中';
            break;
        case 7:
            $statusName = '线下发货';
            break;
        default:
            $statusName = '待付款';
            break;
    }
    return $statusName;
}

/**
 * 发送抽奖礼品
 * @param $song
 * @param $zhi
 * @param $uid
 */
function sendGift($song, $zhi, $uid){
    switch ($song){
        case 1: //积分
            \app\hgapi\model\user\User::incField($uid, 'integral', $zhi);
            break;
        case 2: //赠送优惠券
            $data = [
                'uid' => $uid,
                'cid' => $zhi,
                'time' => time(),
                'status' => 0,
                'type' => 0,
            ];
            \app\hgapi\model\user\UserCoupon::add($data);
            break;
        case 3: //赠送大礼包
            $data = [
                'uid' => $uid,
                'package' => $zhi,
                'yid' => 0,
            ];
            \app\hgapi\model\user\UserPackage::add($data);
            break;
        case 4: //礼品需下单
            break;
    }
}

/**
 * 随机两位小数
 * @param int $min
 * @param int $max
 * @return string
 */
function randomFloat($min = 0, $max = 10){
    $num = $min + mt_rand() / mt_getrandmax() * ($max - $min);
    return sprintf("%.2f", $num);
}
